package com.example.back.service.impl;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.back.dto.req.DoDisableReq;
import com.example.back.dto.req.DoctorListReq;
import com.example.back.dto.req.PharmacistSave;
import com.example.back.dto.resp.DepList;
import com.example.back.dto.resp.InfoPharmacistRsp;
import com.example.back.dto.resp.PharmacisRsp;
import com.example.back.dto.resp.PharmacistInfoRsp;
import com.example.back.feign.FileFeign;
import com.example.back.jpa.HospitalDepartmentRepository;
import com.example.back.jpa.PharmacistRepository;
import com.example.back.mapper.PharmacistMapper;
import com.example.back.service.PharmacistService;
import com.example.common.entity.Hanswer;
import com.example.common.entity.HospitalDepartment;
import com.example.common.entity.Pharmacist;
import com.example.common.sendhttp.CaSendMessage;
import com.example.common.support.ApiException;
import com.example.common.support.Result;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.example.common.utils.RedisUtils;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.javers.spring.annotation.JaversAuditable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author wxy
 * @Date 2021/1/14 13:47
 * @Version 1.0
 */
@Service
public class PharmacistServiceImpl implements PharmacistService {

    @Resource
    PharmacistMapper pharmacistMapper;

    @Resource
    PharmacistRepository pharmacistRepository;

    @Resource
    HospitalDepartmentRepository hospitalDepartmentRepository;

    @Resource
    FileFeign fileFeign;

    @Resource
    private CaSendMessage caSendMessage;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 药师列表
     */
    @Override
    public PageInfo<PharmacisRsp> List(DoctorListReq doctorListReq) {
        PageInfo<PharmacisRsp> objectPageInfo = PageHelper.startPage(doctorListReq.getPage(), doctorListReq.getLimit()).doSelectPageInfo(() -> pharmacistMapper.List(doctorListReq));
        return objectPageInfo;
    }

    /**
     * 启用、禁用
     */
    @Override
    @JaversAuditable
    public Object DoDisable(DoDisableReq doDisableReq) {
        Pharmacist pharmacist = pharmacistRepository.findById(doDisableReq.getDCID()).orElse(null);
        if (pharmacist.getDisable()) {
            pharmacist.setDisable(false);
        } else {
            //启用
            //新增判断电话不能重复
            if (pharmacistRepository.countByPhoneAndAndDisable(pharmacist.getPhone(), true) != 0) {
                throw new ApiException(400, "启用医生中已经存在该手机号码");
            }
            pharmacist.setDisable(true);
        }
        pharmacistRepository.save(pharmacist);
        return null;
    }

    /**
     * 详情
     */
    @Override
    public PharmacistInfoRsp Info(DoDisableReq doDisableReq) {
        List<DepList> depListList = pharmacistMapper.findAllH();
        PharmacistInfoRsp pharmacistInfoRsp = new PharmacistInfoRsp();
        pharmacistInfoRsp.setDepList(depListList);
        if (doDisableReq.getDCID() == 0) {
            return pharmacistInfoRsp;
        }
        Pharmacist pharmacist = pharmacistRepository.findById(doDisableReq.getDCID()).orElse(null);
        HospitalDepartment hospitalDepartment = hospitalDepartmentRepository.findById(pharmacist.getDepartId()).orElse(null);

        InfoPharmacistRsp infoPharmacistRsp = new InfoPharmacistRsp();
        infoPharmacistRsp.setCertificateImg(pharmacist.getCertificateImg());
        infoPharmacistRsp.setCertificateCode(pharmacist.getCertificateCode());
        infoPharmacistRsp.setDepartID(pharmacist.getDepartId());
        infoPharmacistRsp.setIntro(pharmacist.getIntro());
        infoPharmacistRsp.setHead(pharmacist.getHead());
        infoPharmacistRsp.setDepName(hospitalDepartment.getName());
        infoPharmacistRsp.setPhone(pharmacist.getPhone());
        infoPharmacistRsp.setIsExamine(pharmacist.getIsExamine());
        infoPharmacistRsp.setIsOnline(pharmacist.getIsOnline());
        infoPharmacistRsp.setName(pharmacist.getName());
        infoPharmacistRsp.setTitle(pharmacist.getTitle());
        infoPharmacistRsp.setIdUnm(pharmacist.getCardNum());
        pharmacistInfoRsp.setInfo(infoPharmacistRsp);
        return pharmacistInfoRsp;
    }

    /**
     * 上传文件
     */
    @Override
    public HashMap<String, Object> UpLoad(MultipartFile file) {
        Result<Object> result = fileFeign.updateFile(file);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("UpSess", true);
        hashMap.put("url", result.getData());
        return hashMap;
    }

    /**
     * 保存
     */
    @Override
    @JaversAuditable
    public Object Save(PharmacistSave pharmacistSave) {
        Pharmacist pharmacistDb = pharmacistRepository.findByPhone(pharmacistSave.getPhone());
        Map<String, String> map = null;
        if (!ObjectUtils.isEmpty(pharmacistDb) && !pharmacistDb.getDcId().equals(pharmacistSave.getDCID())) {
            throw new ApiException(400, "联系电话已存在，不能重复");
        }
        Pharmacist pharmacistDbByDcId = pharmacistRepository.findById(pharmacistSave.getDCID()).orElse(null);

        // 身份证校验
        CheckUtils.checkNull(pharmacistSave.getIdUnm(), new ApiException(1, "身份证为空"));
        if (!IdcardUtil.isValidCard18(pharmacistSave.getIdUnm())) {
            throw new ApiException(1, "身份证信息有误");
        }

        if (ObjectUtils.isEmpty(pharmacistDbByDcId)) {
            //新增判断电话不能重复
            if (pharmacistRepository.countByPhone(pharmacistSave.getPhone()) != 0) {
                throw new ApiException(400, "当前手机号已经存在");
            }

            // 添加用户
            map = goToAddUser(pharmacistSave.getName(), pharmacistSave.getIdUnm(), pharmacistSave.getPhone());
            redisUtils.set("ca" + pharmacistSave.getPhone(), map.get("msspId") + ":" + map.get("authCode"));

            Pharmacist pharmacist = new Pharmacist();
            pharmacist.setCaCode(map.get("msspId"));
            pharmacist.setDcId(IdUtils.generateId());
            pharmacist.setCreateTime(new Date());
            pharmacist.setCertificateCode(pharmacistSave.getCertificateCode());
            pharmacist.setCertificateImg(pharmacistSave.getCertificateImg());
            pharmacist.setDepartId(pharmacistSave.getDepartID());
            pharmacist.setHead(pharmacistSave.getHead());
            pharmacist.setIntro(pharmacistSave.getIntro());
            pharmacist.setIsExamine(false); // 禁用自动审方
            pharmacist.setIsOnline(pharmacistSave.getIsOnline());
            pharmacist.setName(pharmacistSave.getName());
            pharmacist.setPhone(pharmacistSave.getPhone());
            pharmacist.setTitle(pharmacistSave.getTitle());
            pharmacist.setDisable(false);
            pharmacist.setUserName(pharmacistSave.getPhone());
            pharmacist.setCardNum(pharmacistSave.getIdUnm());
            pharmacistRepository.save(pharmacist);
        } else {
            boolean changePhone = pharmacistDb.getPhone().equals(pharmacistSave.getPhone()) ? false : true;
            //新增判断电话不能重复
            if ((pharmacistRepository.countByPhone(pharmacistSave.getPhone()) > 0 && changePhone) ||
                    (pharmacistRepository.countByPhone(pharmacistSave.getPhone()) > 1 && !changePhone)) {
                throw new ApiException(400, "当前手机号已经存在");
            }
            if (ObjectUtils.isEmpty(pharmacistDbByDcId.getCardNum()) || !pharmacistSave.getIdUnm().equals(pharmacistDb.getCardNum())) {
                // 如果没有ca 用户编号
                if (ObjectUtils.isEmpty(pharmacistDbByDcId.getCaCode())) {
                    map = goToAddUser(pharmacistSave.getName(), pharmacistSave.getIdUnm(), pharmacistSave.getPhone());
                    pharmacistDbByDcId.setCaCode(map.get("msspId"));
                    redisUtils.set("ca" + pharmacistSave.getPhone(), map.get("msspId") + ":" + map.get("authCode"));
                } else {
                    // 删除用户
                    String deleteResult = caSendMessage.deleteUser(pharmacistDb.getCaCode());
                    JSONObject deleteJson = JSONObject.parseObject(deleteResult);
                    if ("SUCCESS".equals(deleteJson.get("message"))) {
                        // 添加用户
                        map = goToAddUser(pharmacistSave.getName(), pharmacistSave.getIdUnm(), pharmacistSave.getPhone());
                        pharmacistDbByDcId.setCaCode(map.get("msspId"));
                        redisUtils.set("ca" + pharmacistSave.getPhone(), map.get("msspId") + ":" + map.get("authCode"));
                    } else {

//                        // 根据身份证获得
//                        String idResult = caSendMessage.idNumQueryUserInfo(doctorReq.getDoctor().getIdUnm());
//                        JSONObject idNumJson = JSONObject.parseObject(idResult);
//
//                        if (CaSendMessage.SUCCESS.equals(idNumJson.get(CaSendMessage.MESSAGE))) {
//                            JSONObject idNumData = JSONObject.parseObject(idNumJson.get("data").toString());
//                            if (idNumData.get(CaSendMessage.NOT_ACTIVE).equals(CaSendMessage.NOT_ACTIVE) || idNumData.get(CaSendMessage.ACTIVE).equals(CaSendMessage.ACTIVE)) {
//                                doctorBaseInfoDb.setCaCode(idNumData.get("msspId").toString());
//                            } else {
//
//                                throw new ApiException(400, jsonObject.get(CaSendMessage.MESSAGE).toString());
//                            }


                        Object message = deleteJson.get("message");
                        throw new ApiException(400, message.toString());
                    }
                }
            }
            pharmacistDbByDcId.setCertificateCode(pharmacistSave.getCertificateCode());
            pharmacistDbByDcId.setCertificateImg(pharmacistSave.getCertificateImg());
            pharmacistDbByDcId.setDepartId(pharmacistSave.getDepartID());
            pharmacistDbByDcId.setHead(pharmacistSave.getHead());
            pharmacistDbByDcId.setIntro(pharmacistSave.getIntro());
            pharmacistDbByDcId.setIsExamine(false); // 禁用自动审方
            pharmacistDbByDcId.setIsOnline(pharmacistSave.getIsOnline());
            pharmacistDbByDcId.setName(pharmacistSave.getName());
            pharmacistDbByDcId.setPhone(pharmacistSave.getPhone());
            pharmacistDbByDcId.setTitle(pharmacistSave.getTitle());
            pharmacistDbByDcId.setCardNum(pharmacistSave.getIdUnm());
            pharmacistRepository.save(pharmacistDbByDcId);
        }
        return map;
    }


    /**
     * Ca 添加user
     *
     * @param name  用户名
     * @param idNum 用户身份证
     * @param phone 用户手机号
     * @return ca用户编号
     */
    private Map<String, String> goToAddUser(String name, String idNum, String phone) {
        String addResult = caSendMessage.addTrustedUser(name, "SF", idNum, phone);
        JSONObject addJson = JSONObject.parseObject(addResult);
        Map<String, String> map = new HashMap<>();
        if ("SUCCESS".equals(addJson.get("message"))) {
            Object data = addJson.get("data");
            JSONObject dataJson = JSONObject.parseObject(data.toString());
            map.put("authCode", dataJson.get("authCode").toString());
            map.put("msspId", dataJson.get("msspId").toString());
            return map;
        } else {
            // 根据身份证获得
            String idResult = caSendMessage.idNumQueryUserInfo(idNum);
            JSONObject idNumJson = JSONObject.parseObject(idResult);

            if (CaSendMessage.SUCCESS.equals(idNumJson.get(CaSendMessage.MESSAGE))) {
                JSONObject idNumData = JSONObject.parseObject(idNumJson.get("data").toString());
                if (idNumData.get("userStatus").equals(CaSendMessage.NOT_ACTIVE) || idNumData.get("userStatus").equals(CaSendMessage.ACTIVE)) {
                    map.put("msspId", idNumData.get("msspId").toString());
                    if (idNumData.get("userStatus").equals(CaSendMessage.NOT_ACTIVE)) {
                        // 获得激活码
                        String authCode = caSendMessage.updateAuthCode(idNumData.get("msspId").toString());
                        map.put("authCode", authCode);
                    }
                    return map;
                } else {
                    throw new ApiException(400, idNumJson.get(CaSendMessage.MESSAGE).toString());
                }
            } else {
                Object message = addJson.get("message");
                throw new ApiException(400, message.toString());
            }
        }
    }
}
